#include "SingleSelectDialog.h"

/*********************| marcos |*********************/

#define CELL_W				300
#define CELL_H				36
#define CELL_TEXT_COLOR			ccc3(48, 50, 47)

/*********************| func in class |*********************/

SingleSelectDialog::SingleSelectDialog()
{ }

SingleSelectDialog::~SingleSelectDialog()
{  }

SingleSelectDialog*SingleSelectDialog::create(const char* titleStr, const char** arr, const uint size, const uint defalut)
{
	SingleSelectDialog* ret = new SingleSelectDialog();
	if (ret && ret->init(titleStr, arr, size, defalut)) {
		ret->autorelease();
		return ret;
	} else {
		delete ret;
		return NULL;
	}
}

bool SingleSelectDialog::init(const char* titleStr, const char** arr, const uint size, const uint defalut)
{
	bool bRet = false;
	do {
		CC_BREAK_IF(!arr);
		CC_BREAK_IF(size < 2);
		CC_BREAK_IF(defalut >= size);
		_textArr = arr;
		_arrSize = size;
		_idx = defalut;
		CC_BREAK_IF(!YesNoPortrol::init(titleStr,
						CCSizeMake(CELL_W, 140 + CELL_H * _arrSize)));
		/* item cells  */
		CCSpriteBatchNode* devideBatch = CCSpriteBatchNode::create("dialog/dline.png", _arrSize - 1);
		CC_BREAK_IF(!devideBatch);
		devideBatch->setPosition(CCPointZero);
		this->addChild(devideBatch);
		CCSprite* devide = NULL;
		CCMenuItemFont* item = NULL;
		uint i = 0;
		const float startX = _bg->boundingBox().getMinX() + 18;
		const float startY = ((CCSprite*)_lineBatch->getChildByTag(0))->boundingBox().getMinY() - 5 -
				     CELL_H / 2;
		const float sc = (CELL_W - 30.0f) / 240.0f;
		while (i < size) {
			item = CCMenuItemFont::create(_textArr[i], this,
						      menu_selector(SingleSelectDialog::selectCB));
			CCLog("%s", _textArr[i]);
			if(!item) return false;
			item->setAnchorPoint(ccp(0, 0.5));
			item->setFontSize(CELL_H - 10);
			item->setFontName("DroidSansFallbackFull");
			item->setColor(CELL_TEXT_COLOR);
			item->setPosition(ccp(startX, startY - i * CELL_H));
			item->setContentSize(CCSizeMake(CELL_W - 20, CELL_H));
			_pMenu->addChild(item, 0, i);
			if (i < size - 1) {
				devide =  CCSprite::createWithTexture(devideBatch->getTexture());
				if(!devide) return false;
				devide->setScaleX(sc);
				devide->setOpacity(175);
				devide->setPosition(ccp(_bg->getPositionX(), item->boundingBox().getMinY()));
				devideBatch->addChild(devide);
			}
			++i;
		}
		item = (CCMenuItemFont*)_pMenu->getChildByTag(_idx);
		_mark = CCSprite::create("dialog/mark.png");
		CC_BREAK_IF(!_mark);
		_mark->setAnchorPoint(ccp(1, 0.5));
		_mark->setScale(0.8f);
		_mark->setPosition(ccp(_bg->boundingBox().getMaxX() - 18, item->getPositionY()));
		this->addChild(_mark);

		bRet = true;
	}while(0);
	return bRet;
}

const size_t SingleSelectDialog::getRetCode()
{
	return _idx;
}

void SingleSelectDialog::selectCB(CCObject* obj)
{
	CCMenuItem* item = (CCMenuItem*)obj;
	_idx = item->getTag();
	_mark->setPositionY(item->getPositionY());
}
